﻿using DIM_Tool;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.IO;
using System.Threading;

namespace DIM_Server.Config_from
{
    public partial class Database_config : UIUserControl
    {
        public Database_config()
        {
            InitializeComponent();
        }

        private void Config_Load(object sender, EventArgs e)
        {
            try
            {
                string Body = File.ReadAllText("database_config.json", System.Text.Encoding.UTF8);

                JObject TEMP = (JObject)JsonConvert.DeserializeObject(Body);

                uiTextBox1.Text = TEMP["服务器IP"].ToString();

                uiTextBox2.Text = TEMP["数据库"].ToString();

                uiTextBox3.Text = TEMP["用户"].ToString();

                uiTextBox4.Text = TEMP["密码"].ToString();
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError(ex.Message);
            }
        }

        private void CESHI()
        {
            try
            {
                string[] str = new string[4];

                str[0] = uiTextBox1.Text;

                str[1] = uiTextBox2.Text;

                str[2] = uiTextBox3.Text;

                str[3] = uiTextBox4.Text;

                Public_Class.Database_Sql = new Database_sql(str);

                Tuple<bool, string> tuple = Public_Class.Database_Sql.Connect_sql();

                if (tuple.Item1)
                {
                    UIMessageBox.ShowSuccess(tuple.Item2);
                }
                else
                {
                    UIMessageBox.ShowError(tuple.Item2);
                }

            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError(ex.Message);
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            UIMessageTip.ShowWarning("等待大约10秒");
            Thread thread = new Thread(CESHI);
            thread.Start();
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            try
            {
                JObject pairs = new JObject
                {
                    { "服务器IP", uiTextBox1.Text },

                    { "数据库", uiTextBox2.Text },

                    { "用户", uiTextBox3.Text },

                    { "密码", uiTextBox4.Text }
                };

                File.WriteAllText("database_config.json", JsonConvert.SerializeObject(pairs));

                UIMessageTip.ShowOk("保存成功");
            }
            catch (Exception ex)
            {
                UIMessageTip.ShowError(ex.Message);
            }
        }
    }
}
